<template>
    <div class="exam-manage">
      <!-- <y-header title="考试管理" left-arrow @click-left="onBack" /> -->
      <YHeader></YHeader>
      <div class="toolbar">
        <van-button type="primary" icon="plus" @click="showCreateExam = true">新建考试</van-button>
      </div>
      
      <div class="exam-list">
        <van-empty v-if="exams.length === 0" description="暂无考试" />
        
        <van-cell-group v-for="exam in exams" :key="exam.id" inset style="margin-bottom: 12px;">
          <van-cell :title="exam.title" is-link @click="viewExamDetail(exam)">
            <template #label>
              <div class="exam-info">
                <div class="exam-time">
                  <van-icon name="clock-o" /> {{ formatDate(exam.startTime) }} ~ {{ formatDate(exam.endTime) }}
                </div>
                <div class="exam-duration">
                  <van-icon name="underway-o" /> 时长：{{ getDurationText(exam) }}
                </div>
              </div>
            </template>
            <template #right-icon>
              <van-tag :type="getStatusTagType(exam.status)">{{ getStatusText(exam.status) }}</van-tag>
            </template>
          </van-cell>
          
          <van-cell title="参与情况">
            <template #value>
              <div class="participation-stats">
                <span>{{ exam.participantCount }}/{{ exam.totalCount }}</span>
                <van-progress :percentage="getParticipationPercentage(exam)" :show-pivot="false" />
              </div>
            </template>
          </van-cell>
          
          <van-cell>
            <template #title>
              <div class="action-buttons">
                <van-button size="small" @click="editExam(exam)" :disabled="exam.status === 'finished'">编辑</van-button>
                <van-button size="small" type="primary" plain @click="viewResults(exam)" :disabled="exam.status === 'not_started'">查看成绩</van-button>
                <van-button size="small" type="danger" @click="confirmDeleteExam(exam)" :disabled="exam.status === 'in_progress'">删除</van-button>
              </div>
            </template>
          </van-cell>
        </van-cell-group>
      </div>
      
      <!-- 创建/编辑考试弹窗 -->
      <van-dialog
        v-model:show="showCreateExam"
        :title="isEditing ? '编辑考试' : '新建考试'"
        show-cancel-button
        @confirm="saveExam"
      >
        <van-form>
          <van-field
            v-model="examForm.title"
            name="title"
            label="标题"
            placeholder="请输入考试标题"
            :rules="[{ required: true, message: '请输入考试标题' }]"
          />
          <van-field
            v-model="examForm.description"
            name="description"
            label="描述"
            type="textarea"
            rows="3"
            placeholder="请输入考试描述"
          />
          <van-field
            readonly
            name="startTime"
            label="开始时间"
            :model-value="examForm.startTime ? formatDate(examForm.startTime) : ''"
            placeholder="请选择开始时间"
            @click="openTimePicker('start')"
          />
          <van-field
            readonly
            name="endTime"
            label="结束时间"
            :model-value="examForm.endTime ? formatDate(examForm.endTime) : ''"
            placeholder="请选择结束时间"
            @click="openTimePicker('end')"
          />
          <van-field
            v-model.number="examForm.totalScore"
            name="totalScore"
            label="总分值"
            type="digit"
            placeholder="请输入总分值"
            :rules="[{ required: true, message: '请输入总分值' }]"
          />
          <van-field name="allowRetake" label="允许重考">
            <template #input>
              <van-switch v-model="examForm.allowRetake" size="20" />
            </template>
          </van-field>
        </van-form>
      </van-dialog>
      
      <!-- 日期时间选择器 -->
      <van-popup v-model:show="showTimePicker" position="bottom">
        <van-datetime-picker
          v-model="selectedTime"
          type="datetime"
          :title="timePickerTitle"
          @confirm="onTimeConfirm"
          @cancel="showTimePicker = false"
        />
      </van-popup>
      
      <!-- 删除确认弹窗 -->
      <van-dialog
        v-model:show="showDeleteConfirm"
        title="确认删除"
        show-cancel-button
        @confirm="deleteExam"
      >
        <p style="padding: 20px 16px;">确定要删除考试"{{ examToDelete?.title }}"吗？该操作不可撤销。</p>
      </van-dialog>
    </div>
  </template>
  
  <script setup lang="ts">
  import { ref, computed, onMounted } from 'vue';
  import { useRouter, useRoute } from 'vue-router';
  import { showToast, showSuccessToast } from 'vant';
  import YHeader from '@/components/YHeader.vue';
  
  interface Exam {
    id: string;
    title: string;
    description: string;
    startTime: string;
    endTime: string;
    totalScore: number;
    allowRetake: boolean;
    status: 'not_started' | 'in_progress' | 'finished';
    participantCount: number;
    totalCount: number;
  }
  
  const router = useRouter();
  const route = useRoute();
  const courseId = computed(() => route.query.courseId as string);
  
  // 模拟数据
  const exams = ref<Exam[]>([
    {
      id: '1',
      title: '期中考试：Vue基础',
      description: 'Vue3组件、生命周期和响应式原理',
      startTime: '2023-11-10T09:00:00',
      endTime: '2023-11-10T11:00:00',
      totalScore: 100,
      allowRetake: false,
      status: 'finished',
      participantCount: 40,
      totalCount: 42
    },
    {
      id: '2',
      title: '期末考试：Vue进阶',
      description: 'Vue Router、Pinia状态管理和组合式API',
      startTime: '2023-12-20T14:00:00',
      endTime: '2023-12-20T17:00:00',
      totalScore: 150,
      allowRetake: true,
      status: 'not_started',
      participantCount: 0,
      totalCount: 42
    }
  ]);
  
  const showCreateExam = ref(false);
  const showTimePicker = ref(false);
  const showDeleteConfirm = ref(false);
  const isEditing = ref(false);
  const examToDelete = ref<Exam | null>(null);
  const selectedTime = ref(new Date());
  const timePickerType = ref<'start' | 'end'>('start');
  const timePickerTitle = computed(() => timePickerType.value === 'start' ? '选择开始时间' : '选择结束时间');
  
  const examForm = ref({
    id: '',
    title: '',
    description: '',
    startTime: '',
    endTime: '',
    totalScore: 100,
    allowRetake: false
  });
  
  onMounted(async () => {
    // 实际项目中这里应该调用API获取考试列表
    // if (courseId.value) {
    //   try {
    //     const res = await getExamList(courseId.value);
    //     exams.value = res.data;
    //   } catch (error) {
    //     console.error('获取考试列表失败', error);
    //   }
    // }
  });
  
  const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
  };
  
  const getDurationText = (exam: Exam) => {
    const startTime = new Date(exam.startTime).getTime();
    const endTime = new Date(exam.endTime).getTime();
    const duration = (endTime - startTime) / (1000 * 60); // 分钟
    
    if (duration < 60) {
      return `${duration}分钟`;
    } else {
      const hours = Math.floor(duration / 60);
      const minutes = duration % 60;
      return minutes > 0 ? `${hours}小时${minutes}分钟` : `${hours}小时`;
    }
  };
  
  const getParticipationPercentage = (exam: Exam) => {
    if (exam.totalCount === 0) return 0;
    return Math.round((exam.participantCount / exam.totalCount) * 100);
  };
  
  const getStatusTagType = (status: string) => {
    switch (status) {
      case 'not_started': return 'primary';
      case 'in_progress': return 'warning';
      case 'finished': return 'success';
      default: return 'default';
    }
  };
  
  const getStatusText = (status: string) => {
    switch (status) {
      case 'not_started': return '未开始';
      case 'in_progress': return '进行中';
      case 'finished': return '已结束';
      default: return '未知';
    }
  };
  
  const viewExamDetail = (exam: Exam) => {
    router.push({
      path: `/classroom/manage/exams/detail`,
      query: {
        courseId: courseId.value,
        examId: exam.id
      }
    });
  };
  
  const editExam = (exam: Exam) => {
    isEditing.value = true;
    examForm.value = {
      id: exam.id,
      title: exam.title,
      description: exam.description,
      startTime: exam.startTime,
      endTime: exam.endTime,
      totalScore: exam.totalScore,
      allowRetake: exam.allowRetake
    };
    showCreateExam.value = true;
  };
  
  const resetExamForm = () => {
  examForm.value = {
    id: '',
    title: '',
    description: '',
    startTime: '',
    endTime: '',
    totalScore: 100,
    allowRetake: false
  };
  isEditing.value = false;
};

const openTimePicker = (type: 'start' | 'end') => {
  timePickerType.value = type;
  selectedTime.value = type === 'start' && examForm.value.startTime ? 
    new Date(examForm.value.startTime) : 
    type === 'end' && examForm.value.endTime ?
    new Date(examForm.value.endTime) :
    new Date();
  showTimePicker.value = true;
};

const onTimeConfirm = (time: Date) => {
  if (timePickerType.value === 'start') {
    examForm.value.startTime = time.toISOString();
  } else {
    examForm.value.endTime = time.toISOString();
  }
  showTimePicker.value = false;
};

const saveExam = async () => {
  // 验证开始时间和结束时间
  if (!examForm.value.startTime || !examForm.value.endTime) {
    showToast('请选择开始时间和结束时间');
    return;
  }
  
  const startTime = new Date(examForm.value.startTime).getTime();
  const endTime = new Date(examForm.value.endTime).getTime();
  
  if (startTime >= endTime) {
    showToast('结束时间必须晚于开始时间');
    return;
  }
  
  // 实际项目中这里应该调用API保存考试
  try {
    if (isEditing.value) {
      // 修改现有考试
      const index = exams.value.findIndex(e => e.id === examForm.value.id);
      if (index !== -1) {
        exams.value[index] = {
          ...exams.value[index],
          title: examForm.value.title,
          description: examForm.value.description,
          startTime: examForm.value.startTime,
          endTime: examForm.value.endTime,
          totalScore: examForm.value.totalScore,
          allowRetake: examForm.value.allowRetake
        };
      }
      showSuccessToast('考试已更新');
    } else {
      // 创建新考试
      const newId = String(Date.now());
      const now = new Date().getTime();
      let status: 'not_started' | 'in_progress' | 'finished' = 'not_started';
      
      if (now > endTime) {
        status = 'finished';
      } else if (now >= startTime && now <= endTime) {
        status = 'in_progress';
      }
      
      exams.value.push({
        id: newId,
        title: examForm.value.title,
        description: examForm.value.description,
        startTime: examForm.value.startTime,
        endTime: examForm.value.endTime,
        totalScore: examForm.value.totalScore,
        allowRetake: examForm.value.allowRetake,
        status: status,
        participantCount: 0,
        totalCount: 42 // 这里应该是学生总数
      });
      showSuccessToast('考试已创建');
    }
    
    resetExamForm();
  } catch (error) {
    console.error('保存考试失败', error);
    showToast('操作失败');
  }
};

const confirmDeleteExam = (exam: Exam) => {
  examToDelete.value = exam;
  showDeleteConfirm.value = true;
};

const deleteExam = async () => {
  if (!examToDelete.value) return;
  
  // 实际项目中这里应该调用API删除考试
  // try {
  //   await deleteExamApi(examToDelete.value.id);
  //   exams.value = exams.value.filter(e => e.id !== examToDelete.value?.id);
  //   showSuccessToast('考试已删除');
  // } catch (error) {
  //   console.error('删除考试失败', error);
  //   showToast('删除失败');
  // }
  
  // 模拟删除
  exams.value = exams.value.filter(e => e.id !== examToDelete.value?.id);
  showSuccessToast('考试已删除');
};

const viewResults = (exam: Exam) => {
  router.push({
    path: `/classroom/manage/exams/results`,
    query: {
      courseId: courseId.value,
      examId: exam.id
    }
  });
};
</script>

<style scoped>
.exam-manage {
  background-color: #f7f8fa;
  min-height: 100vh;
  padding-bottom: 20px;
}

.toolbar {
  padding: 16px;
  display: flex;
  justify-content: flex-end;
}

.exam-list {
  padding: 0 8px;
}

.exam-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
  margin-top: 4px;
}

.exam-time, .exam-duration {
  display: flex;
  align-items: center;
  color: #646566;
  font-size: 13px;
}

.exam-time .van-icon, .exam-duration .van-icon {
  margin-right: 4px;
  font-size: 14px;
}

.participation-stats {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
}

.participation-stats span {
  font-size: 12px;
  color: #646566;
  margin-bottom: 4px;
}

.action-buttons {
  display: flex;
  gap: 8px;
}
</style>